package cn.btks.databasehandler.handle.task;

import cn.btks.commonserver.result.Constants;
import cn.btks.commonserver.result.ResultState;
import cn.btks.databasehandler.handle.pojo.BackUpConfig;
import cn.btks.databasehandler.handle.pojo.BackUpResult;
import cn.btks.databasehandler.handle.service.BackUpConfigService;
import cn.btks.databasehandler.handle.service.BackUpResultService;
import cn.btks.databasehandler.handle.util.QuartzUtil;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import lombok.SneakyThrows;
import org.apache.commons.io.IOUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Author lijun
 * @Date 2020/12/28 13:18
 */
public class BackUpTask extends QuartzJobBean {

    @Autowired
    BackUpConfigService backUpConfigService;

    @Autowired
    BackUpResultService backUpResultService;

    @Value("${spring.datasource.url}")
    private String url;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    @Value("${mysqldump.path}")
    private String mysqldumpPath;

    @SneakyThrows
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        String filePathUp = (String) jobExecutionContext.getJobDetail().getJobDataMap().get("filePath");
        File fileUp = new File(filePathUp);
        if(!fileUp.exists()){
            fileUp.mkdirs();
        }
        String mysqlBaseDir = QuartzUtil.getBaseDir(url,username,password);
        BackUpConfig backUpConfig = (BackUpConfig) jobExecutionContext.getJobDetail().getJobDataMap().get("config");
        if (backUpConfig != null) {
            String path = mysqlBaseDir + File.separator +"bin/";
            String root = this.username;
            String dataBase = backUpConfig.getSelectDBName();
            String password = this.password;
            Date currentDate = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
            String strDate = simpleDateFormat.format(currentDate);
            String sqlName = strDate + ".sql";
            String cmd = "";
            switch (backUpConfig.getBackUpMode()) {
                case 0:
                    cmd = path + "mysqldump -h 127.0.0.1 -u" + root + " -p" + password + " -R -c --set-charset=utf8 " + dataBase + " ";
                    break;
                case 1:
                    String selectTableName = backUpConfig.getSelectTableName();
                    if (!StringUtils.isEmpty(selectTableName)) {
                        String[] selectNames = selectTableName.split(";");
                        if (selectNames != null && selectNames.length > 0) {
                            String tableNames = " ";
                            for (String item : selectNames) {
                                tableNames += item + " ";
                            }
                            cmd = path + "mysqldump -h 127.0.0.1 -u" + root + " -p" + password + " -R -c --set-charset=utf8 " + dataBase + " " + tableNames + " ";
                        }
                    }
                    break;
            }
            try {
                Runtime rt = Runtime.getRuntime();
                Process process = rt.exec(cmd);
                InputStream in = process.getInputStream();
                InputStreamReader xx = new InputStreamReader(in, "utf8");
                String inStr;
                StringBuffer sb = new StringBuffer("");
                String outStr;
                BufferedReader br = new BufferedReader(xx);
                while ((inStr = br.readLine()) != null) {
                    sb.append(inStr + "\r\n");
                }
                outStr = sb.toString();
                String filePath = filePathUp + sqlName;
                FileOutputStream fout = new FileOutputStream(filePath);
                OutputStreamWriter writer = new OutputStreamWriter(fout, "utf8");
                writer.write(outStr);
                writer.flush();
                in.close();
                xx.close();
                br.close();
                writer.close();
                fout.close();
                //更新该备份配置为启动状态
                int result = backUpConfigService.updateIsStarted(backUpConfig.getId(),1);
                if(result > 0){
                    //更新配置启动结果
                    BackUpResult backUpResult = new BackUpResult();
                    File file = new File(filePath);
                    if(file.exists()){
                        Calendar calendar = Calendar.getInstance();
                        Date dateTimeNow = calendar.getTime();
                        backUpResult.setHandleDateTime(dateTimeNow);
                        backUpResult.setResult("Success");
                        backUpResult.setFilePath(filePath);
                        backUpResult.setConfigId(backUpConfig.getId());
                        backUpResult.setConfigName(backUpConfig.getConfigName());
                        backUpResult.setBackUpMode(backUpConfig.getBackUpMode());
                        backUpResult.setBackUpCycle(backUpConfig.getBackUpCycle());
                        backUpResult.setBackUpTime(jobExecutionContext.getJobRunTime());
                        backUpResultService.save(backUpResult);
                    }
                }
            } catch (Exception e) {
                BackUpResult backUpResult = new BackUpResult();
                Calendar calendar = Calendar.getInstance();
                Date dateTimeNow = calendar.getTime();
                backUpResult.setHandleDateTime(dateTimeNow);
                backUpResult.setResult("Failed");
                backUpResult.setConfigId(backUpConfig.getId());
                backUpResult.setConfigName(backUpConfig.getConfigName());
                backUpResult.setBackUpMode(backUpConfig.getBackUpMode());
                backUpResult.setBackUpCycle(backUpConfig.getBackUpCycle());
                backUpResult.setException(e.getMessage());
                backUpResult.setBackUpTime(jobExecutionContext.getJobRunTime());
                backUpResultService.save(backUpResult);
                e.printStackTrace();
            }
        }
    }
}
